package com.yonyou.pmclouds.basecom.filter;

import com.alibaba.dubbo.rpc.*;
import com.yonyou.pmclouds.basecom.multilanguage.Language;
import com.yonyou.pmclouds.basecom.runtime.DevRuntimeEnvironment;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import lombok.extern.slf4j.Slf4j;

import java.util.Locale;

@Slf4j
public class DubboProviderContextFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String lang = RpcContext.getContext().getAttachment(RuntimeEnvironment.KEY_LANG);
        log.info("step into {} method:{}", invoker.getInterface(), invocation.getMethodName());
        if (lang == null) {
            lang = Locale.CHINA.getLanguage();
        }
        String country = RpcContext.getContext().getAttachment(RuntimeEnvironment.KEY_COUNTRY);
        if (country == null) {
            country = Locale.CHINA.getCountry();
        }
        String ds = RpcContext.getContext().getAttachment(RuntimeEnvironment.KEY_DATA_SOURCE);

        RuntimeEnvironment.setLanguage(Language.getLanguage(new Locale(lang, country)));
        RuntimeEnvironment.setDataSource(ds);
        RuntimeEnvironment.setTenantId(RpcContext.getContext().getAttachment(RuntimeEnvironment.KEY_TENANT_ID));
        RuntimeEnvironment.setLoginUserId(RpcContext.getContext().getAttachment(RuntimeEnvironment.KEY_LOGIN_USER));
        DevRuntimeEnvironment.setDestHost(RpcContext.getContext().getAttachment(DevRuntimeEnvironment.DEV_DEST_KEY));
        long startTime = System.currentTimeMillis();
        try {
            return invoker.invoke(invocation);
        } finally {
            log.trace("==========the method is {}, exe time is {} ", invocation.getMethodName(), System.currentTimeMillis() - startTime);

        }
    }
} 